package com.dy.design_pattern_study.utils;

import org.springframework.util.StringUtils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @CreateBy zhangdingyi
 * @Date 2023-03-23
 * @Content 获取地址的类
 */
public class Utils {
    /**
     * 打印内存地址
     * @param t
     * @return
     * @param <T>
     */
    public static <T> String getAddress(T t){
        String address = Integer.toHexString(System.identityHashCode(t));
        //System.out.println("Address = " + address);
        return address;
    }

    /**
     * 对象深度复制(对象必须是实现了Serializable接口)
     *
     * @param obj 任意对象
     * @return T
     * @author Muscleape
     * @date 2018/8/10 14:39
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        T clonedObj = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            //写入对象
            oos.writeObject(obj);
            oos.close();

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            //读取对象
            clonedObj = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clonedObj;
    }

    /**
     * 日期转换成字符串
     * @param time
     * @param format
     * @return
     */
    public static String dateToString(LocalDateTime time, String format){

        String formatDefault = "yyyy-MM-dd";

        if (StringUtils.hasLength(format)){
            formatDefault = format;
        }

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(formatDefault);
        String convertTime = dtf.format(time);
        return convertTime;
    }

    /**
     * 利用反射来获取实例
     * @param className
     * @return
     * @param <T>
     */
    public static <T> T getObject(String className){
        //选择生产工厂(通过反射创建对象)
        T result = null;
        try {
            //利用类名，来创建类实例
            result = (T) Class.forName(className).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
